/*
 * jxSwing Project (2014)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2014
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxSwing.component.comboBox;

import java.awt.Component;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import org.jxSwing.component.comboBox.cellRenderer.LabelListRenderer;
import org.jxSwing.font.MyFont;

/**
 * @author Denilson Edinaldo Pinto
 * @porject jxSwing
 * @package org.jxSwing.component.comboBox
 * @date 05/02/2014 - 22:30:13
 */
public class FontComboBox extends ComboBox<Font> {
	
	private static final long serialVersionUID = -7207165641322961846L;
	
	private Component component = null;
	
	/**
	 * 
	 */
	public FontComboBox() {
	
		this(null);
	}
	
	/**
	 * @param component
	 */
	public FontComboBox(final Component component) {
	
		super(MyFont.getFontsAvailable());
		
		this.component = component;
		
		initGUI();
	}
	
	/**
	 * 
	 */
	private void initGUI() {
	
		setRenderer(new LabelListRenderer());
		
		//
		if(component != null) {
			
			setSelected(component.getFont().getName());
		}
		
		addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(final ItemEvent itemEvent) {
			
				setFont(getSelectedItem());
				
				//
				if(component != null) {
					
					final Font font = component.getFont();
					
					component.setFont(new Font(getSelectedItem().getName(), font.getStyle(), font.getSize()));
				}
			}
		});
	}
	
	/**
	 * @param fontName
	 * @return index
	 */
	public int getIndexByName(final String fontName) {
	
		//
		for(int index = 0; index < getItemCount(); index++) {
			
			//
			if(getItemAt(index).getName().equals(fontName)) {
				
				return index;
			}
		}
		
		return -1;
	}
	
	/**
	 * @param fontName
	 */
	public void setSelected(final String fontName) {
	
		setSelectedIndex(getIndexByName(fontName));
	}
}
